package com.baomidou.ant.service.impl;

import com.baomidou.ant.entity.*;
import com.baomidou.ant.mapper.PointsStoreMapper;
import com.baomidou.ant.service.*;
import com.baomidou.ant.vo.Request.RequestExchangeGoodsVo;
import com.baomidou.ant.vo.Request.RequestListGoodsVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.dc.pr.PRError;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 *
 * 每一次物品兑换,涉及到以下问题：
 * 1，先判断兑换条件，是否满足：饰品（只能换一次）？道具（有的只能换一次，用完才能再换，有的可以换多次）？礼包（有的只能换一次，用完才能再换）？
 * 2，每次兑换道具时，要先进行bagcontent判断，有这条字段且持有数量大于，即说明你背包里有这个道具，唯一性道具则不能再换
 * 3，兑换后生成相应的兑换清单,并且对数量为0，新兑换的物品userBag加一个已使用格子数(UsedAmount+1)
 *
 *
 * @author jobob
 * @since 2021-03-24
 */
@Service
public class PointsStoreServiceImpl extends ServiceImpl<PointsStoreMapper, PointsStore> implements IPointsStoreService {
    @Value("${file.upload.path}")
    private String uploadPath;
    @Autowired
    private IExchangeListService exchangeListService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IUserBagService userBagService;
    @Autowired
    private IBagContentService bagContentService;

    @Override
    public String upload(MultipartFile file) {
        // 获取上传文件名
        String filename = file.getOriginalFilename();
        // 定义上传文件保存路径
        String path = uploadPath+"goodsImages/";
        // 新建文件
        File filepath = new File(path, filename);
        // 判断路径是否存在，如果不存在就创建一个
        if (!filepath.getParentFile().exists()) {
            filepath.getParentFile().mkdirs();
        }
        try {
            file.transferTo(new File(path + File.separator + filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "goodsImages/"+ filename;
    }

    @Override
    public IPage<PointsStore> list(RequestListGoodsVo requestListGoodsVo) {
        IPage<PointsStore> storeIPage=new Page<>(requestListGoodsVo.getDisplayStart(), requestListGoodsVo.getDisplayLength());
        QueryWrapper<PointsStore> queryWrapper=new QueryWrapper<>();
        //只显示在售的
        queryWrapper.eq("status","1");
        if(StringUtils.isNotEmpty(requestListGoodsVo.getGoodsName())){
            queryWrapper.like("goods_name", requestListGoodsVo.getGoodsName());
        }
        if(StringUtils.isNotEmpty(requestListGoodsVo.getGoodsType())){
            queryWrapper.eq("goods_type",requestListGoodsVo.getGoodsName());
        }
        IPage<PointsStore> pointsStoreIPage=page(storeIPage,queryWrapper);
        if(pointsStoreIPage.getRecords().size()<=0) {
            return null;
        }
        return pointsStoreIPage.convert(goodsList -> {
            PointsStore pointsStore=new PointsStore();
            BeanUtils.copyProperties(goodsList,pointsStore);
            return pointsStore;
        });
    }

    @Override
    public Integer exchangeGoods(RequestExchangeGoodsVo requestExchangeGoodsVo) {
        //判断库存是否充足
        PointsStore goods=getById(requestExchangeGoodsVo.getGoodsId());
        if(goods.getGoodsAmount()<=0){
            return 404;
        }
        //是否为非卖品（0代表非卖品）
        if(Objects.equals(goods.getIsQuality(), "0"))
            return -400;
        //判断积分是否充足
        User user=userService.getById(requestExchangeGoodsVo.getUserId());
        if(user.getPoints()<goods.getPrice()){
            return 0;
        }
        //判断背包是否满了
        QueryWrapper<UserBag> userBagQueryWrapper=new QueryWrapper<>();
        userBagQueryWrapper.eq("user_id",requestExchangeGoodsVo.getUserId());
        UserBag userBag=userBagService.getOne(userBagQueryWrapper);
        if(Objects.equals(userBag.getTotalAmount(), userBag.getUsedAmount())){
            return -3;
        }

        //先拿到背包中该物品信息，为空就代表没换过这个
        QueryWrapper<BagContent> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",requestExchangeGoodsVo.getUserId());
        queryWrapper.eq("goods_id",requestExchangeGoodsVo.getGoodsId());
        BagContent bagContent=bagContentService.getOne(queryWrapper);

        //判断是唯一性商品道具还是饰品礼包(饰品和礼包只能换一次)
        if(ObjectUtils.isNotEmpty(bagContent)&& Objects.equals(goods.getGoodsType(), "饰品")){
            //是饰品且背包里有
            return -1;
        }else if(Objects.equals(goods.getGoodsType(), "礼包")&&ObjectUtils.isNotEmpty(bagContent)&&bagContent.getAmount()>0){
            return -1;
        }else if( Objects.equals(goods.getGoodsType(), "道具")){
            //是唯一性道具且背包里有(1代表唯一性)
            if(ObjectUtils.isNotEmpty(bagContent)&&Objects.equals(goods.getIsQuality(), "1")&&bagContent.getAmount()>0){
                return -2;
            }
        }

        //判断是不是只能购买一次的道具
        if(ObjectUtils.isNotEmpty(bagContent)&&Objects.equals(goods.getIsQuality(),"3")){
            return 500;
        }

        //没有任何问题即可兑换
        //保存订单纪录
        ExchangeList exchangeList=new ExchangeList();
        exchangeList.setUserId(requestExchangeGoodsVo.getUserId());
        exchangeList.setUserName(user.getUsername());
        exchangeList.setGoodsId(requestExchangeGoodsVo.getGoodsId());
        exchangeList.setGoodsName(goods.getGoodsName());
        exchangeListService.save(exchangeList);
        //库存更新
        goods.setGoodsAmount(goods.getGoodsAmount()-1);
        saveOrUpdate(goods);
        //积分更新
        user.setPoints(user.getPoints()-goods.getPrice());
        userService.saveOrUpdate(user);
        //背包内容物增加
        if(ObjectUtils.isEmpty(bagContent)){
            BagContent bagContent1=new BagContent();
            bagContent1.setGoodsId(goods.getId());
            bagContent1.setUserId(user.getId());
            bagContent1.setAmount(1);
            bagContent1.setGoodsName(goods.getGoodsName());
            bagContentService.save(bagContent1);
            //放入背包中-----没有的道具才会usedAmount+1
            userBag.setUsedAmount(userBag.getUsedAmount()+1);
            userBagService.saveOrUpdate(userBag);
        }else {
            bagContent.setAmount(bagContent.getAmount()+1);
            bagContentService.saveOrUpdate(bagContent);
            //放入背包中-----没有的道具才会usedAmount+1
            if(bagContent.getAmount()==0){
                userBag.setUsedAmount(userBag.getUsedAmount()+1);
                userBagService.saveOrUpdate(userBag);
            }
        }

        return 1;
    }
}
